package com.kun.valiant.clue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.kun.valiant.assignment.domain.Assignment;
import com.kun.valiant.assignment.service.IAssignmentService;
import com.kun.valiant.business.domain.Business;
import com.kun.valiant.business.service.IBusinessService;
import com.kun.valiant.clue.domain.Clue;
import com.kun.valiant.clue.domain.vo.ClueDetails;
import com.kun.valiant.clue.domain.vo.ClueSummary;
import com.kun.valiant.clue.domain.vo.ClueVO;
import com.kun.valiant.clue.mapper.ClueMapper;
import com.kun.valiant.clue.service.IClueService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.valiant.common.constant.ValiantConstants;
import com.kun.valiant.common.core.domain.AjaxResult;
import com.kun.valiant.common.core.domain.model.EchartsPoint;
import com.kun.valiant.common.core.domain.model.LineChartData;
import com.kun.valiant.common.utils.SecurityUtils;
import com.kun.valiant.follow.domain.FollowRecord;
import com.kun.valiant.follow.service.IFollowRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 线索 服务实现类
 * </p>
 *
 * @author fangkun
 * @since 2023-06-08
 */
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements IClueService {

    @Autowired
    IAssignmentService assignmentService;

    @Autowired
    ClueMapper clueMapper;

    @Autowired
    IFollowRecordService followRecordService;

    @Autowired
    IBusinessService businessService;

    @Override
    @Transactional
    public AjaxResult addClue(Clue clue) {
        //添加之前判断该线索是否已经存在
        LambdaQueryWrapper<Clue> wrapper = new LambdaQueryWrapper<Clue>().eq(Clue::getPhone, clue.getPhone()).eq(Clue::getDelFlag, 0);
        Clue one = getOne(wrapper);
        if (one != null){
            return AjaxResult.error("该线索已经存在");
        }
        clue.setNextTime(LocalDateTime.now().plusHours(ValiantConstants.NEXT_FOLLOW_time));
        clue.setCreateBy(SecurityUtils.getUsername());
        clue.setCreateTime(LocalDateTime.now());
        clue.setDelFlag(0);

        //添加线索
        save(clue);
        //默认添加人为当前线索分配人
        Assignment assignment = new Assignment();
        assignment.setAssignId(clue.getClueId());
        assignment.setLatest(true);
        assignment.setType(ValiantConstants.CLUE_TYPE);
        assignment.setUserName(SecurityUtils.getUsername());
        assignment.setUserId(SecurityUtils.getUserId());
        assignment.setDeptId(SecurityUtils.getDeptId());
        assignment.setCreateBy(SecurityUtils.getUsername());
        assignment.setCreateTime(LocalDateTime.now());
        assignmentService.save(assignment);
        return AjaxResult.success("添加成功");
    }

    @Override
    public List<ClueSummary> selectAllList(ClueVO clueVO) {
        return clueMapper.selectAllList(clueVO);
    }

    @Override
    public AjaxResult getClueDetailsByClueId(Long clueId) {
        ClueDetails clueDetails = clueMapper.getClueDetailsByClueId(clueId);
        return AjaxResult.success(clueDetails);
    }

    @Override
    @Transactional
    public AjaxResult clueFollow(ClueDetails clueDetails) {
        //更新clue表
        Clue clue = new Clue();
        BeanUtils.copyProperties(clueDetails,clue);
        clue.setStatus(ValiantConstants.CLUE_FOLLOWING);
        updateById(clue);
        //添加follow表
        FollowRecord followRecord = new FollowRecord();
        followRecord.setCreateBy(SecurityUtils.getUsername());
        followRecord.setCreateTime(LocalDateTime.now());
        followRecord.setType(ValiantConstants.CLUE_TYPE);
        followRecord.setInfo(clueDetails.getRecord());
        followRecord.setAssignId(clueDetails.getClueId());
        followRecordService.save(followRecord);
        return AjaxResult.success("跟进成功");
    }

    @Override
    @Transactional
    public AjaxResult invalidClueFollow(ClueDetails clueDetails) {
        //首先，如果失败次数超过三次，就变成伪线索
        Clue byId = getById(clueDetails.getClueId());
        if (byId.getFailCount() == 3){
            LambdaUpdateWrapper<Clue> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(Clue::getStatus,ValiantConstants.CLUE_INVALIDATE)
                    .eq(Clue::getClueId,clueDetails.getClueId());
            update(wrapper);
            return AjaxResult.success("已设置为无效线索");
        }
        //线索变得fail_count字段 +1
        LambdaUpdateWrapper<Clue> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.setSql("fail_count=fail_count+1").eq(Clue::getClueId,clueDetails.getClueId());
        update(updateWrapper);
        //然后跟进表添加记录
        FollowRecord followRecord = new FollowRecord();
        followRecord.setCreateBy(SecurityUtils.getUsername());
        followRecord.setCreateTime(LocalDateTime.now());
        followRecord.setType(ValiantConstants.CLUE_TYPE);
        followRecord.setInfo(clueDetails.getRecord());
        followRecord.setAssignId(clueDetails.getClueId());
        followRecordService.save(followRecord);
        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult getClueSummaryById(Long clueId) {
        return AjaxResult.success(getById(clueId));
    }

    @Override
    public AjaxResult updateClue(Clue clue) {
        return updateById(clue) ? AjaxResult.success("更新成功") : AjaxResult.error("更新失败");
    }

    @Override
    public AjaxResult deleteClueById(Long[] clueIds) {
        LambdaUpdateWrapper<Clue> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Clue::getDelFlag,1).in(Clue::getClueId,clueIds);
        return update(wrapper) ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    @Override
    @Transactional
    public AjaxResult clue2Business(Long clueId) {
        Clue clue = getById(clueId);
        Business business = new Business();
        BeanUtils.copyProperties(clue,business);
        business.setCreateBy(SecurityUtils.getUsername());
        business.setCreateTime(LocalDateTime.now());
        business.setEndTime(null);
        business.setFailCount(0);
        business.setNextTime(null);
        business.setRemark(null);
        business.setUpdateBy(null);
        business.setUpdateTime(null);
        business.setNextTime(LocalDateTime.now().plusHours(ValiantConstants.NEXT_FOLLOW_time));
        business.setStatus(ValiantConstants.BUSINESS_ALLOCATED);
        //删除线索
        LambdaUpdateWrapper<Clue> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Clue::getDelFlag,1).eq(Clue::getClueId,clueId);
        update(wrapper);
        //添加商机
        businessService.save(business);
        //默认情况下，将商机分配给admin，将来由admin再将商机分配给不同的客户专员
        Assignment assignment = new Assignment();
        assignment.setUserName(ValiantConstants.ADMIN_USERNAME);
        assignment.setType(ValiantConstants.BUSINESS_TYPE);
        assignment.setCreateBy(SecurityUtils.getUsername());
        assignment.setCreateTime(LocalDateTime.now());
        assignment.setAssignId(business.getBusinessId());
        assignment.setDeptId(ValiantConstants.ADMIN_DEPT_ID);
        assignment.setUserId(ValiantConstants.ADMIN_ID);
        assignmentService.save(assignment);
        return AjaxResult.success("线索成功转换为商机");
    }

    @Override
    public AjaxResult clueAnalysisData(ClueVO clueVO) {
        if (clueVO.getParams().get("beginTime") == null || clueVO.getParams().get("endTime") == null) {
            clueVO.getParams().put("beginTime",LocalDateTime.now().minusMonths(1));
            clueVO.getParams().put("endTime",LocalDateTime.now());
        }
        List<EchartsPoint> increaseClue = clueMapper.increaseClue(clueVO);
        List<EchartsPoint> totalClue = clueMapper.totalClue(clueVO);
        LineChartData lineChartData = new LineChartData();
        lineChartData.setIncrease(increaseClue);
        lineChartData.setTotal(totalClue);
        return AjaxResult.success(lineChartData);
    }


}
